package com.ktjy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjy.mapper.SysRoleMapper;
import com.ktjy.pojo.SysRole;
import com.ktjy.pojo.SysRoleRight;
import com.ktjy.service.ISysRoleRightService;
import com.ktjy.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jjx
 * @since 2025-01-09
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
    @Autowired
    ISysRoleRightService iSysRoleRightService;
    
    @Override
    @Transactional
    public boolean save(SysRole sysRole, String[] rightCode) {
        //1. 保存角色表
        boolean flag1=this.save(sysRole);
        //2. 保存角色权限中间表
        boolean flag2=false;
        if(rightCode!=null){
            List<SysRoleRight> list=new ArrayList<>();
            for (String s : rightCode) {
                SysRoleRight sysRoleRight=new SysRoleRight();
                sysRoleRight.setRfRoleId(sysRole.getRoleId());
                sysRoleRight.setRfRightCode(s);
                list.add(sysRoleRight);
            }
            flag2=iSysRoleRightService.saveBatch(list);
        }
        return flag1 && flag2;
    }

    @Override
    @Transactional
    public boolean update(SysRole sysRole, String[] rightCode) {
        //1.修改角色表
        boolean flag1=this.updateById(sysRole);

        //2.先删除中间表数据
        QueryWrapper qw=new QueryWrapper();
        qw.eq("rf_role_id",sysRole.getRoleId());
        boolean flag2=iSysRoleRightService.remove(qw);
        //3.在新增中间表数据
        boolean flag3=false;
        if(rightCode!=null){
            List<SysRoleRight> list=new ArrayList<>();
            for (String s : rightCode) {
                SysRoleRight sysRoleRight=new SysRoleRight();
                sysRoleRight.setRfRoleId(sysRole.getRoleId());
                sysRoleRight.setRfRightCode(s);
                list.add(sysRoleRight);
            }
            flag3=iSysRoleRightService.saveBatch(list);
        }
        return flag1 && flag2 && flag3;
    }

    @Override
    @Transactional
    public boolean delete(Long id) {
        //1.先删除中间表的数据
        QueryWrapper qw=new QueryWrapper();
        qw.eq("rf_role_id",id);
        boolean flag1=iSysRoleRightService.remove(qw);
        //2.再删角色表
        boolean flag2=this.removeById(id);

        return flag1 && flag2;
    }
}
